from api import ApiServer
import json

class PollServer(ApiServer):
  def get(self):
    pass

  def post(self):
    self.get()

  def display(self):
    list_type = self.request.get('list_type')
    output = []
    if list_type == 'pollsoffriend':
      # Example Query:
      # /display?list_type=pollsoffriend&
      #                   [opensocial_viewer_id=[ID]]
      self._PollsOfFriends(output)
    elif list_type == 'optionsofpoll':
      # Example Query:
      # /display?list_type=optionsofpoll&
      #          poll_id=[KEY]&
      #         [opensocial_viewer_id=[ID]]
      self._OptionsOfPoll(output)
    elif list_type == 'pollsofuser':
      # Example Query:
      # /display?list_type=pollsofuser&
      #          creator_id=[ID]&
      #         [opensocial_viewer_id=[ID]]
      self._PollsOfUser(self.request.get("creator_id"), None, output)
    elif list_type == 'testsocial':
      self._handlesocial(output)
    self.response.out.write(json.write(output))
    pass

  def create(self):
    pass

  # Returns output.append({creator_id:[id],
  #                       description:[text],
  #                       poll_id:[id]})
  def _PollsOfUser(self, user_id, user_name, output):
    viewer_id = self.request.get('opensocial_viewer_id')
    results = Poll.gql('WHERE creator_id=:user_id', user_id=user_id)
    for poll in results:
      if self._checkPollAccess(poll, viewer_id):
        out = {'creator_id': user_id,
               'creator_name': user_name,
               'description': poll.description,
               'poll_id': str(poll.key())}
        output.append(out)

  # Returns output += [{creator_id:[id],
  #                     description:[text],
  #                     poll_id:[id]}]
  def _PollsOfFriends(self, output):
    friends = self._get_friends_data(self.request.get('opensocial_viewer_id'))
    for friend in friends:
      self._PollsOfUser(friend.get_id(), friend.get_display_name(), output)
  # Returns output.append([options[text]])
  def _OptionsOfPoll(self, output):
    viewer_id = self.request.get('opensocial_viewer_id')
    poll_id = self.request.get("poll_id")
    if poll_id:
      poll = Poll.get(poll_id)
      if poll and self._checkPollAccess(poll, viewer_id):
        output+=poll.options
